//判断是否是JSON数据
/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== "object") {
    throw new Error("error arguments", "deepClone");
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === "object") {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}
export function isJSON(str) {
  if (typeof str != "string") {
    // 1、传入值必须是 字符串
    //console.log("It is not a string! [" + str + "]");
    return false;
  }

  try {
    var obj = JSON.parse(str); // 2、仅仅通过 JSON.parse(str)，不能完全检验一个字符串是JSON格式的字符串
    if (typeof obj == "object" && obj) {
      //3、还必须是 object 类型
      return true;
    } else {
      return false;
    }
  } catch (e) {
    //console.log("error：[" + str + "] !!! " + e);
    return false;
  }
}

export function mapToLang(val) {
  switch (val) {
    case "en":
      return "en";
    case "ru":
      return "ru";
    case "kz":
      return "kz";
    default:
      return "zh";
  }
}

export function toTranslateLang(list, locale) {
  if (Array.isArray(list)) {
    list.forEach((item) => {
      if (isJSON(item.name)) {
        item.translateName = JSON.parse(item.name)[mapToLang(locale)];
      } else {
        item.translateName = item.name;
      }
      if (Array.isArray(item.childList)) {
        toTranslateLang(item.childList, locale);
      }
    });
  }
  // console.log("list", list);
  return list;
}
